﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace BinaryTools {
    public partial class AsciiChart : UserControl {
        private static readonly string[] NAMES =
            {
                "NULL","Start of heading","Start of text","End of text","End of transmission","Enquire",
                "Acknowlege","Bell","Backspace","Horizontal tab","NL line feed, new line",
                "Vertical tab","NP form feed, new page","Carriage return","Shift out","Shift in",
                "Data link escape","Device control 1","Device control 2","Device control 3","Device control 4",
                "Negative acknowlege","Synchronous idle","End of transmission block","Cancel",
                "End of medium","Substitute","Escape","File seperator","Group seperator","Record seperator",
                "Unit seperator","Space"
            };
        private readonly Bitmap _charmap;

        public AsciiChart() {
            _charmap = new Bitmap(GetType().Assembly.GetManifestResourceStream("BinaryTools.charmap.bmp"));

            InitializeComponent();

            for (int i = 0; i < 255; i++) {
                string decimalText = string.Format("{0}", i);
                string hexText = string.Format("0x{0:X2}", i);
                string octalText = string.Format("0{0}", Convert.ToString(i, 8));
                string nameText = i < NAMES.Length ? NAMES[i] : "";
                string imageKey = hexText;

                _asciiImage.Images.Add(imageKey, GetImage(i));

                ListViewItem lvi = _asciiChart.Items.Add("", imageKey);
                lvi.SubItems.Add(decimalText);
                lvi.SubItems.Add(hexText);
                lvi.SubItems.Add(octalText);
                lvi.SubItems.Add(nameText);
            }
        }

        private Image GetImage(int asciiNumber) {
            Bitmap img = new Bitmap(24, 24);
            using (Graphics g = Graphics.FromImage(img)) {
                int srcX = 19 * asciiNumber;
                Rectangle destRect = new Rectangle(0, 0, 18, 24);
                Rectangle srcRect = new Rectangle(srcX, 0, 18, 24);
                g.DrawImage(_charmap, destRect, srcRect, GraphicsUnit.Pixel);
            }
            return img;
        }
    }
}